package com.yunxi.service.localService.impl.sto;

import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.bizToHub.pojo.VehicleStockShiftVO;
import com.yunxi.bizToHub.service.VehicleStockManageDubboService;
import com.yunxi.core.page.PageHelperPlus;
import com.yunxi.core.service.ServiceImplPlus;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.dao.order.VehicleStockMapper;
import com.yunxi.model.order.PmsVehicleStock;
import com.yunxi.model.sto.StoFrozenHis;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.service.localService.sto.StoChangeStorageService;
import com.yunxi.service.localService.sto.StoFrozenHisService;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.service.localService.sto.VehicleStockMService;
import com.yunxi.sto.pojo.*;
import com.yunxi.vehicle.pojo.VehicleCatalogListVO;
import com.yunxi.vehicle.pojo.VehicleSeriesListVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 经销商车辆库存 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-05-29
 */
@Service
public class VehicleStockMServiceImpl extends ServiceImplPlus<VehicleStockMapper, PmsVehicleStock> implements VehicleStockMService {

    @Autowired
    @Qualifier(value = "stoChangeStorageServiceImpl")
    StoChangeStorageService stoChangeStorageService;

    @Autowired
    @Qualifier(value = "vehicleStockManageDubboServiceImplBiz")
    VehicleStockManageDubboService vehicleStockManageDubboService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    @Autowired
    @Qualifier(value = "stoFrozenHisServiceImpl")
    StoFrozenHisService stoFrozenHisService;

    private static final Logger logger = LoggerFactory.getLogger(VehicleStockMServiceImpl.class);

    /**
     * 车辆冻结
     * @param list
     */
    @Override
    public void frozen(List<VehicleStockFrozenVO> list, String isFrozen, Integer frozenReasonKey, String userId) throws Exception {
        if(list != null && list.size() > 0){
            for(VehicleStockFrozenVO vo : list){
                String id = vo.getBusinessKey();
                PmsVehicleStock pmsVehicleStock = baseMapper.selectById(id);
                if(pmsVehicleStock != null){
                    pmsVehicleStock.setVehicleIsFrozen(isFrozen);
                    pmsVehicleStock.setUpdateBy(userId);
                    baseMapper.updateById(pmsVehicleStock);
                    String vin = pmsVehicleStock.getVin();
                    VehicleStockShiftVO vehicleStockShiftVO1 = new VehicleStockShiftVO();
                    List<VehicleStockShiftVO> vehicleStockShiftVO = stoChangeStorageService.queryStockChangeInfo(vin);
                    QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("VIN",vin);
                    VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
                    if(vehicleOffline != null){
                        vehicleOffline.setVehicleIsFrozen(Integer.parseInt(isFrozen));
                        vehicleOffline.setFrozenReasonKey(frozenReasonKey);
                        vehicleOfflineService.updateById(vehicleOffline);
                    }
                    if(vehicleStockShiftVO != null && vehicleStockShiftVO.size() > 0){
                        vehicleStockShiftVO1 = vehicleStockShiftVO.get(0);
                        //冻结
                        if(isFrozen != null && isFrozen.equals("1")){
                            vehicleStockShiftVO1.setBwart(DictConstant.VEHICLE_STATE_FROZEN);
                        }
                        //解冻
                        else {
                            vehicleStockShiftVO1.setBwart(DictConstant.VEHICLE_STATE_UNFROZEN);
                        }
                        //整车库存同步接口,PMS推送到SAP
                        vehicleStockManageDubboService.vehicleStockShiftPms2Sap(vehicleStockShiftVO1);
                    }
                    else{
                        logger.debug("操作失败,整车库存同步接口推送消息为空!");
                        //throw new Exception("操作失败,整车库存同步接口推送消息为空!");
                    }

                    //插入冻结/解冻历史
                    newFrozenHis(isFrozen, vo, vin,2);
                }
                else{
                    throw new Exception("操作失败,无法根据主键id"+id+"找到对应库存记录!");
                }
            }
        }
        else {
            throw new Exception("操作失败,主键id集合为空!");
        }
    }

    /**
     * 新增车辆冻结解冻历史
     * @param isFrozen
     * @param vo
     * @param vin
     */
    @Override
    public void newFrozenHis(String isFrozen, VehicleStockFrozenVO vo, String vin,Integer frozenType) {
        if(StringUtils.isNotEmpty(isFrozen) && isFrozen.equals("1")){
            StoFrozenHis stoFrozenHis = new StoFrozenHis();
            stoFrozenHis.setFrozenType(frozenType);//1库位冻结,2车辆冻结
            stoFrozenHis.setBusinessKey(vin);
            stoFrozenHis.setFrozenDate(new Date());
            if(vo != null){
                stoFrozenHis.setFrozenReason(vo.getFrozenReason());
                stoFrozenHis.setRemark(vo.getRemark());
            }
            stoFrozenHisService.saveOrUpdate(stoFrozenHis);
        }
        else if(StringUtils.isNotEmpty(isFrozen) && isFrozen.equals("0")){
            StoFrozenHis stoFrozenHis = stoFrozenHisService.getByBusinessKey(vin);
            if(stoFrozenHis != null){
                stoFrozenHis.setUnfrozenDate(new Date());
                stoFrozenHisService.saveOrUpdate(stoFrozenHis);
            }
        }
    }

    /**
     * 导出车辆冻结明细
     * @return
     * @throws Exception
     */
    @Override
    public List<VehicleStockFrozenListVO> exportFrozenList() throws Exception {
        return baseMapper.exportFrozenList();
    }

    /**
     * 库存报表
     * @param vehicleStockReportVO
     * @return
     */
    @Override
    public List<VehicleStockReportVO> stockReport(VehicleStockReportVO vehicleStockReportVO) {
        return baseMapper.stockReport(vehicleStockReportVO);
    }

    /**
     * 库存报表详情
     * @param vehicleStockReportDetailVO
     * @return
     */
    @Override
    public List<VehicleStockReportDetailVO> stockReportDetail(VehicleStockReportDetailVO vehicleStockReportDetailVO) {
        return baseMapper.stockReportDetail(vehicleStockReportDetailVO);
    }

    /**
     * 维修出入库
     * @param list
     * @param isRepairOut
     * @throws Exception
     */
    @Override
    public void repairInOut(List<String> list, Integer isRepairOut) throws Exception {
        /*if(list != null && list.size() > 0){
            for(String id : list){
                PmsVehicleStock pmsVehicleStock = baseMapper.selectById(id);
                if(pmsVehicleStock != null){
                    //维修出库
                    if(isRepairOut == 1){
                        StoStockOutPlanVO stoStockOutPlanVO = new StoStockOutPlanVO();
                        stoStockOutPlanVO.setVin(pmsVehicleStock.getVin());
                        stoStockOutPlanVO.setStorageCode(pmsVehicleStock.getStorageLocation());
                        stoStockOutPlanVO.setStockOutType("12");//送修出库
                        stoStockOutPlanDubboService.saveOrUpdate(stoStockOutPlanVO);
                    }
                    //维修入库
                    else if(isRepairOut == 0){
                        StoStockInPlanVO stoStockInPlanVO = new StoStockInPlanVO();
                        stoStockInPlanVO.setVin(pmsVehicleStock.getVin());
                        stoStockInPlanVO.setStockInType("4");//送修入库
                        stoStockInPlanDubboService.saveAndUpdate(stoStockInPlanVO);
                    }
                }
                else{
                    throw new Exception("操作失败,无法根据主键id找到对应库存记录!");
                }
            }
        }
        else {
            throw new Exception("操作失败,主键id集合为空!");
        }*/
    }

    /**
     * 根据选装包代码集合,查询名称拼接
     * @param list
     * @return
     */
    @Override
    public String queryVehiclePackageByList(List<String> list) {
        return baseMapper.queryVehiclePackageByList(list);
    }


    @Override
    public void updateDealerStock(String vin) {
        PmsVehicleStock pmsVehicleStock = new PmsVehicleStock();
        pmsVehicleStock.setVin(vin);
        String currentUserStr = RpcContext.getContext().getAttachment("currentUser");
        LoginInfo loginInfo = JSONObject.parseObject(currentUserStr, LoginInfo.class);
        pmsVehicleStock.setPartnerCode(loginInfo.getPartnerCode());
        baseMapper.updateDealerStock(pmsVehicleStock);
    }

    @Override
    public List<VehicleSeriesListVO> seriesList() throws Exception {
        return baseMapper.seriesList();
    }

    @Override
    public List<VehicleCatalogListVO> catalogList() throws Exception {
        return baseMapper.catalogList();
    }

    @Override
    public List<VehicleStockQueryVO> export(VehicleStockQueryVO vehicleStockQueryVO) throws Exception {
        Map map = BeanTools.bean2map(vehicleStockQueryVO);
        return baseMapper.queryByList(map);
    }

    /**
     * 查看库存厂端在库车辆的详细信息
     * @param vehicleId
     * @return
     */
    @Override
    public VehicleStockVO findByVehicleId(String vehicleId) {
        return baseMapper.findByVehicleId(vehicleId);
    }

    @Override
    public PageInfo maintainPageByVo(Object vo, Integer pageNum, Integer pageSize) {
        Map map = BeanTools.bean2map(vo);
        PageHelperPlus.startPage(pageNum,pageSize);
        List<Object> list = baseMapper.queryMaintainByList(map);
        PageInfo<Object> pageInfo = new PageInfo<Object>(list);
        return pageInfo;
    }

    /**
     * 厂端库存车辆保养列表
     * @param vo
     * @return
     */
    @Override
    public List<VehicleStockQueryVO> maintainList(VehicleStockQueryVO vo) {
        Map map = BeanTools.bean2map(vo);
        List<VehicleStockQueryVO> list = baseMapper.queryMaintainByList(map);
        return list;
    }


    @Override
    public List<VehicleStockMaintainVO> mainTainExport(VehicleStockQueryVO vehicleStockQueryVO) {
        Map map = BeanTools.bean2map(vehicleStockQueryVO);
        List<VehicleStockMaintainVO> list = baseMapper.exportList(map);
        return list;
    }

    /**
     * 体验车查询
     * @param vehicleStockQueryVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<VehicleStockQueryVO> sharePage(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws Exception {
        PageHelperPlus.startPage(pageNum,pageSize);
        List<VehicleStockQueryVO> list = baseMapper.sharePage(vehicleStockQueryVO);
        PageInfo<VehicleStockQueryVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 体验车管理
     * @param vehicleStockQueryVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<VehicleStockQueryVO> newSharePage(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws Exception {
        PageHelperPlus.startPage(pageNum,pageSize);
        List<VehicleStockQueryVO> list = baseMapper.newSharePage(vehicleStockQueryVO);
        PageInfo<VehicleStockQueryVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 畅想车分页
     * @param vehicleStockQueryVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<VehicleStockQueryVO> financePage(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws Exception {
        PageHelperPlus.startPage(pageNum,pageSize);
        List<VehicleStockQueryVO> list = baseMapper.financePage(vehicleStockQueryVO);
        PageInfo<VehicleStockQueryVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<VehicleStockQueryVO> shareList(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws Exception {
        PageHelperPlus.startPage(pageNum,pageSize);
        List<VehicleStockQueryVO> list = baseMapper.shareList(vehicleStockQueryVO);
        PageInfo<VehicleStockQueryVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据渠道代码查询类型
     * @param partnerCode
     * @return
     * @throws Exception
     */
    @Override
    public String queryPartnerType(String partnerCode) throws Exception {
        return baseMapper.queryPartnerType(partnerCode);
    }
}
